package com.hibase.quartz.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hibase.common.exception.HibaseAssert;
import com.hibase.quartz.config.job.ConcurrentDynamicJob;
import com.hibase.quartz.config.job.SerializeDynamicJob;
import com.hibase.quartz.entity.MdsJob;
import org.quartz.*;

/**
 * @Description: TODO
 * @Author: liuyunlei
 * @Date: 2020/11/18 13:25
 * @Version: 1.0
 */
public class MdsJobUtils {

    //获取JobDetail,JobDetail是任务的定义,而Job是任务的执行逻辑,JobDetail里会引用一个Job Class来定义
    public static JobDetail getJobDetail(JobKey jobKey, MdsJob mdsJob, JobDataMap map) {

        if (mdsJob.getIsSerialization().equals(Boolean.TRUE)) {

            //并发任务
            return JobBuilder.newJob(ConcurrentDynamicJob.class)
                    .withIdentity(jobKey)
                    .withDescription(mdsJob.getDescription())
                    .setJobData(map)
                    .storeDurably()
                    .build();

        } else {

            //串行任务
            return JobBuilder.newJob(SerializeDynamicJob.class)
                    .withIdentity(jobKey)
                    .withDescription(mdsJob.getDescription())
                    .setJobData(map)
                    .storeDurably()
                    .build();

        }

    }

    //获取Trigger (Job的触发器,执行规则)
    public static Trigger getTrigger(MdsJob job) {
        return TriggerBuilder.newTrigger()
                .withIdentity(job.getName(), job.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
                .build();
    }

    //获取JobKey,包含Name和Group
    public static JobKey getJobKey(MdsJob job) {
        return JobKey.jobKey(job.getName(), job.getJobGroup());
    }

    public static JobDataMap getJobDataMap(MdsJob job) {

        return new JobDataMap(BeanUtil.beanToMap(job));
    }

    public static MdsJob JobDataMapToMdsJob(JobDataMap map) {

        return BeanUtil.mapToBean(map.getWrappedMap(), MdsJob.class, true);
    }

    public static String timeZoneHandler(String cron, String timeZone) {

        if (StrUtil.isBlank(timeZone)) {
            timeZone = "UTC+8";
        }


        HibaseAssert.isTrue(timeZone.contains("UTC"),"时区不合法！");


        if(true){
            return cron;
        }

        StringBuilder finalCron = new StringBuilder();

        //获取时区数据
        Integer hour = Integer.valueOf(timeZone.split("TC")[1]);

        //需要将时区对应到 UTC+0 时区
        String[] cronStr = cron.split(" ");


        if ("*".equals(cronStr[2])||cronStr[2].contains("/")) {

            return cron;

        }

        Integer cronHour = hour + Integer.valueOf(cronStr[2]) < 0 ? 24 + (hour + Integer.valueOf(cronStr[2])) : hour + Integer.valueOf(cronStr[2]);

        cronStr[2] = cronHour.toString();

        for (String str : cronStr) {

            finalCron.append(" ").append(str);
        }

        return finalCron.toString().trim();
    }

}
